package com.tan.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tan.common.domain.user.SysDict;
import com.tan.common.domain.user.SysDict;
import com.tan.common.domain.user.SysDictType;
import com.tan.common.dto.user.DictCreateDTO;
import com.tan.common.dto.user.DictCreateDTO;
import com.tan.common.dto.user.DictUpdateDTO;
import com.tan.common.mapper.user.SysDictMapper;
import com.tan.common.mapstruct.user.DictConvert;
import com.tan.common.mapstruct.user.DictVoConvert;
import com.tan.common.query.user.DictQuery;
import com.tan.common.tools.ConvertTool;
import com.tan.common.tools.PageTool;
import com.tan.common.tools.StreamTool;
import com.tan.common.vo.user.DictMapVO;
import com.tan.common.vo.user.DictTypeVO;
import com.tan.common.vo.user.DictVO;
import com.tan.core.enums.RedisKeyEnum;
import com.tan.core.utils.ExceptionTool;
import com.tan.core.utils.RedissonTool;
import com.tan.core.utils.StringUtils;
import com.tan.core.utils.ThreadPoolTool;
import com.tan.user.service.ISysDictService;
import com.tan.user.service.ISysDictTypeService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Tan-Bowen
 * @description
 * @date 2025/2/19 11:13
 */
@Slf4j
@Service
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements ISysDictService {

    @Resource
    private RedissonTool redissonTool;

    @Resource
    private ThreadPoolTool threadPoolTool;

    @Resource
    private ISysDictTypeService dictTypeService;

    @Override
    public void createDict(DictCreateDTO dictCreateDTO) {
        SysDict Dict = DictConvert.INSTANCE.dtoDomain(dictCreateDTO);
        SysDict type = this.baseMapper.selectOne(Wrappers.lambdaQuery(SysDict.class)
                .eq(SysDict::getTypeCode, dictCreateDTO.getTypeCode())
                .eq(SysDict::getValue, dictCreateDTO.getValue())
        );
        ExceptionTool.systemError(type != null, "字典已存在");
        int count = this.baseMapper.insert(Dict);
        ExceptionTool.operateSqlError(count, "添加字典失败");
    }


    @Override
    public void updateDict(DictUpdateDTO DictUpdateDTO) {
        SysDict dict = DictConvert.INSTANCE.dtoDomain(DictUpdateDTO);
        if (StringUtils.isNotNull(DictUpdateDTO, DictCreateDTO::getValue)) {
            SysDict type = this.baseMapper.selectOne(Wrappers.lambdaQuery(SysDict.class)
                    .eq(SysDict::getTypeCode, DictUpdateDTO.getTypeCode())
                    .eq(SysDict::getValue, DictUpdateDTO.getValue())
                    .ne(SysDict::getId, DictUpdateDTO.getId()));
            ExceptionTool.systemError(type != null, "字典已存在");
        }
        int count = this.baseMapper.updateById(dict);
        this.clearRedis(dict.getTypeCode());
        ExceptionTool.operateSqlError(count, "修改字典失败");
    }

    @Override
    public List<SysDict> dictAll() {
        return this.baseMapper.selectList(Wrappers.lambdaQuery(SysDict.class).eq(SysDict::getStatus, true));
    }

    @Override
    public List<DictVO> dictVOS() {
        return DictConvert.INSTANCE.toTargets(this.dictAll());
    }

    // todo 放入redis
    @Override
    public List<DictMapVO> dictMap() {
        List<DictMapVO> result = new ArrayList<>();
        List<DictVO> dictVOS = this.dictVOS();
        Map<String, List<DictVO>> map = StreamTool.group(dictVOS, DictVO::getTypeCode);
        List<SysDictType> types = dictTypeService.dictTypes();
        Map<String, String> typeMap = StreamTool.toMap(types, SysDictType::getCode, SysDictType::getName);
        map.forEach((k, v) -> {
            String name = typeMap.getOrDefault(k, "");
            DictMapVO mapVO = DictMapVO.builder().name(name).typeCode(k).dictList(v).build();
            result.add(mapVO);
        });
        return result;
    }


    @Override
    public List<DictVO> getDict(String typeCode) {
        String key = RedisKeyEnum.DICT_TYPE_CODE.createKey(typeCode);
        List<DictVO> dicts = redissonTool.getObject(key);
        if (!ExceptionTool.isEmpty(dicts)) {
            return dicts;
        }
        List<SysDict> sysDicts = this.baseMapper.selectList(Wrappers.lambdaQuery(SysDict.class).eq(SysDict::getTypeCode, typeCode)
                .eq(SysDict::getStatus, true).orderByAsc(SysDict::getSort));
        dicts = ConvertTool.toTarget(DictConvert.class, sysDicts);
        redissonTool.cacheObjWeek(key, dicts);
        return dicts;
    }

    @Override
    public IPage<DictVO> DictPages(DictQuery query) {
        LambdaQueryWrapper<SysDict> wrapper = Wrappers.lambdaQuery(SysDict.class);
        wrapper.eq(query.getTypeCode() != null, SysDict::getTypeCode, query.getTypeCode());
        wrapper.eq(query.getValue() != null, SysDict::getValue, query.getValue());
        wrapper.like(com.tan.core.utils.StringUtils.isNotBlank(query.getName()), SysDict::getName, query.getName());
        wrapper.orderByDesc(SysDict::getId, SysDict::getTypeCode);
        IPage<SysDict> pages = this.baseMapper.selectPage(new Page<>(query.getCurrent(), query.getSize()), wrapper);
        return PageTool.convert(pages, DictVoConvert.class);
    }

    @Override
    public void delDict(Long dictId) {
        SysDict dict = this.baseMapper.selectById(dictId);
        ExceptionTool.isNullError(dict, "字典不存在");
        int count = this.baseMapper.deleteById(dictId);
        ExceptionTool.operateSqlError(count, "删除字典失败");
        this.clearRedis(dict.getTypeCode());
    }

    public void clearRedis(String typeCode) {
        threadPoolTool.execute(() -> {
            redissonTool.delCache(typeCode);
        });
    }

}
